import { usePermissionStore } from "@/store";
import { Directive, DirectiveBinding } from "vue";

/** 按钮权限 */
export const button: Directive<HTMLElement, boolean> = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionStore = usePermissionStore();
    const { value } = binding;
    if (value) {
      const hasPerm = permissionStore.buttonList.some((item) => {
        return value.includes(item.permission);
      });

      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need perms! Like v-button=\"['sys:user:add','sys:user:edit']\"");
    }
  },
};

/** 页面局部菜单权限 */
export const menu: Directive<HTMLElement, boolean> = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionStore = usePermissionStore();
    const { value } = binding;
    if (value) {
      const hasPerm = permissionStore.flatMenuList.some((item) => {
        return value.includes(item.routerName);
      });

      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need perms! Like v-menu=\"['sys:user:add','sys:user:edit']\"");
    }
  },
};
